package com.geeyuu.android.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.customview.Rotate3DAnimation;
import com.geeyuu.android.databases.DataBaseHelper;
import com.geeyuu.android.model.ChatInfo;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.LogUtil;

public class ChatActivity extends BaseActivity {

    private ListView mChatListView;
    private BaseAdapter mChatAdapter;
    private long friendUid;

    private View textViews;
    private View voiceViews;
    private Rotate3DAnimation leftAnimation;
    private Rotate3DAnimation rightAnimation;
    private Rotate3DAnimation leftAnimation2;
    private Rotate3DAnimation rightAnimation2;
    private static final int duration = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isWatingMsgFromService = true;
        super.TAG = "ChatActivity";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_layout);

        mHandler = new MyHandler(this);
        friendUid = getIntent().getLongExtra("uid", -1);

        initTitleViews();
        initContentViews();
        
        startBindService();
        
    }
    
    private void initTitleViews() {
        
        Button topLeftButton = (Button)findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.title_back_icon, 0, R.drawable.title_icon_tab2, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 5), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if(null == vl){
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        }else{
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        topLeftButton.setOnClickListener(mOnClickListener);
        
        TextView topLeftTextView = (TextView)findViewById(R.id.top_left_text_view);
        topLeftTextView.setText("张某某");
        topLeftTextView.setVisibility(View.VISIBLE);
        
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.to_voice_button:
                toVoicetMode();
                break;
                
            case R.id.to_text_button:
                toTextMode();
                break;
                
            case R.id.to_profile_or_to_chat_button:
                startActivity(new Intent(ChatActivity.this, FriendProfileAvtivity.class).putExtra("uid", friendUid));
                overridePendingTransition(R.anim.in2, R.anim.out2);
                break;
                
            case R.id.top_left_button:
                finish();
                if(Activity0.isFromActivity0){
                    overridePendingTransition(R.anim.in2, R.anim.out2);
                }
                break;
                
            case R.id.send_msg_button:
                if(!CommonUtil.isEmpty(currentInput)){
                    Bundle bundle = new Bundle();
                    bundle.putInt("chatMsgType", ChatInfo.MSG_TYPE_TEXT);
                    bundle.putLong("friendUid", friendUid);
                    bundle.putString("msgContent", currentInput);
                    sendMsgToService(ProtocolCommand.CMD_SEND_CHAT_MSG, bundle);
                    System.out.println("send");
                }
                break;
            }
        }
    };
    
    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        System.out.println("rec");
        switch (cmd) {
        case ProtocolCommand.CMD_SEND_CHAT_MSG:
            requery();
            break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(Activity0.isFromActivity0){
            overridePendingTransition(R.anim.in2, R.anim.out2);
        }
    }

    private Handler mHandler;
    private static final int CODE_SHOW_RECORDING_TIPS = 0;
    private static final int CODE_ON_ERROR = 1;
    private static final int CODE_CHANGE_FLAG_TRUE = 2;
    private static final int CODE_STOP_RECORD = 3;

    static class MyHandler extends Handler {

        public final WeakReference<ChatActivity> mActivity;

        public MyHandler(Activity activity) {
            mActivity = new WeakReference<ChatActivity>((ChatActivity) activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case CODE_SHOW_RECORDING_TIPS:
                mActivity.get().recordProgressBar.setVisibility(View.GONE);
                mActivity.get().recordingTips.setVisibility(View.VISIBLE);
                break;
            case CODE_ON_ERROR:
                mActivity.get().recordProgressBar.setVisibility(View.GONE);
                mActivity.get().recordingTips.setVisibility(View.GONE);
                break;
            case CODE_CHANGE_FLAG_TRUE:
                mActivity.get().isCanRecord = true;
                break;
            case CODE_STOP_RECORD:
                if (mActivity.get().recordProgressBar.getVisibility() == View.VISIBLE) {
                    mActivity.get().recordProgressBar.setVisibility(View.GONE);
                }
                if (mActivity.get().recordingTips.getVisibility() == View.VISIBLE) {
                    mActivity.get().recordingTips.setVisibility(View.GONE);
                }
                if (mActivity.get().recordThread.isAlive() || !mActivity.get().voiceFile.exists()) {
                    if(mActivity.get()._stopRecordCount < 5){
                        this.sendEmptyMessageDelayed(CODE_STOP_RECORD, 200);
                    }else{
                        LogUtil.e(mActivity.get().TAG, "停止不了录音！ RecordThreadIsAlive:" + mActivity.get().recordThread.isAlive());
                        LogUtil.e(mActivity.get().TAG, "停止不了录音！ RecordFileIsExist:" + mActivity.get().voiceFile.exists());
                        mActivity.get()._stopRecordCount = 0;
                        mActivity.get().isLoopStop = true;
                    }
                    mActivity.get()._stopRecordCount++;
                } else {
                    try {
                        mActivity.get().mMediaRecorder.stop();
                        mActivity.get().stopRecordCount = 0;
                        mActivity.get().isLoopStop = true;
                        LogUtil.d(mActivity.get().TAG, "确实停止了录音");
                    } catch (Exception e) {
                        LogUtil.e(mActivity.get().TAG, "停止录音异常", e);
                        if (mActivity.get().stopRecordCount < 5) {
                            this.sendEmptyMessageDelayed(CODE_STOP_RECORD, 200);
                        } else {
                            LogUtil.e(mActivity.get().TAG, "实在是停止不了录音！！！！！！！！！", e);
                            mActivity.get().stopRecordCount = 0;
                            mActivity.get().isLoopStop = true;
                        }
                        mActivity.get().stopRecordCount++;
                    }
                }
                break;
            }
        }

    }

    int stopRecordCount = 0;
    int _stopRecordCount = 0;
    Thread recordThread;
    File voiceFile;
    boolean isCanRecord = true;
    boolean isLoopStop = true;
    Toast toast;

    private OnTouchListener mOnTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                if (isCanRecord && isLoopStop) {
                    if (recordProgressBar.getVisibility() != View.VISIBLE) {
                        recordProgressBar.setVisibility(View.VISIBLE);
                    }
                    voiceFile = new File(GeeConstants.PATH_TEMP_FILE_FOLDER, String.valueOf(System.currentTimeMillis()));
                    recordThread = new Thread(new RecordThread(voiceFile.getAbsolutePath()));
                    recordThread.start();
                }else{
                    if(null == toast){
                        toast = Toast.makeText(ChatActivity.this, "您录音得太频繁了,请稍等", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                    }
                    toast.cancel();
                    toast.show();
                }
            } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                if(isCanRecord && isLoopStop){
                    isLoopStop = false;
                    mHandler.sendEmptyMessageDelayed(CODE_STOP_RECORD, 200);
                    isCanRecord = false;
                    mHandler.sendEmptyMessageDelayed(CODE_CHANGE_FLAG_TRUE, 1200);
                }
            }
            return false;
        }
    };

    private MediaRecorder mMediaRecorder;

    private class RecordThread implements Runnable {

        private final String voiceFilePath;

        public RecordThread(String voiceFilePath) {
            this.voiceFilePath = voiceFilePath;
        }

        @Override
        public void run() {
            if (null == mMediaRecorder) {
                mMediaRecorder = new MediaRecorder();
            }
            try {
                mMediaRecorder.reset();
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            } catch (Exception e) {
                LogUtil.e(TAG, "预备前阶段异常", e);
                return;
            }
            mMediaRecorder.setOutputFile(voiceFilePath);
            mMediaRecorder.setOnErrorListener(new OnErrorListener() {
                @Override
                public void onError(MediaRecorder mr, int what, int extra) {
                    LogUtil.e(TAG, "what:" + what + " extra:" + extra);
                }
            });
            mMediaRecorder.setOnInfoListener(new OnInfoListener() {
                @Override
                public void onInfo(MediaRecorder mr, int what, int extra) {
                    LogUtil.i(TAG, "what:" + what + " extra:" + extra);
                }
            });
            try {
                mMediaRecorder.prepare();
            } catch (Exception e) {
                LogUtil.e(TAG, "录音prepare阶段异常", e);
                mHandler.sendEmptyMessage(CODE_ON_ERROR);
                return;
            }
            try {
                mMediaRecorder.start();
                mHandler.sendEmptyMessage(CODE_SHOW_RECORDING_TIPS);
            } catch (Exception e) {
                LogUtil.e(TAG, "录音start阶段异常", e);
                mHandler.sendEmptyMessage(CODE_ON_ERROR);
            }
        }
    }

    // 录音的代码
    View recordProgressBar;
    View recordingTips;
    String currentInput;

    private void initContentViews() {
        
        textViews = findViewById(R.id.text_views);
        findViewById(R.id.send_msg_button).setOnClickListener(mOnClickListener);
        EditText textMsgEdit = (EditText)findViewById(R.id.chat_text_msg_edit);
        textMsgEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentInput = s.toString();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void afterTextChanged(Editable s) {}
        });
        
        voiceViews = findViewById(R.id.voice_views);
        findViewById(R.id.to_voice_button).setOnClickListener(mOnClickListener);
        findViewById(R.id.to_text_button).setOnClickListener(mOnClickListener);
        
        View bottomViews = findViewById(R.id.bottom_views_container);
        bottomViews.findViewById(R.id.exchanged_private_photo).setOnClickListener(mOnClickListener);
        
        View sendLoc = bottomViews.findViewById(R.id.send_my_loc);
        sendLoc.setVisibility(View.VISIBLE);
        sendLoc.setOnClickListener(mOnClickListener);
        View sendFlower = bottomViews.findViewById(R.id.send_flower);
        sendFlower.setVisibility(View.VISIBLE);
        sendFlower.setOnClickListener(mOnClickListener);

        findViewById(R.id.record_button).setOnTouchListener(mOnTouchListener);
        recordProgressBar = findViewById(R.id.record_progress);
        recordingTips = findViewById(R.id.recording_tips);

        TextView lookFriendProfileButton = (TextView) findViewById(R.id.to_profile_or_to_chat_button);
        lookFriendProfileButton.setOnClickListener(mOnClickListener);

//        // 我
//        ContentValues cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.CHAT_SEND_STATE, ChatInfo.SEND_STATE_SENDING);
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_TEXT);
//        cv.put(ChatInfo.SEND_UID, GeePrefrence.getMyUid(this));
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//
//        // 对方
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "你更好");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.CHAT_SEND_STATE, ChatInfo.SEND_STATE_SENDING);
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_TEXT);
//        cv.put(ChatInfo.SEND_UID, friendUid);
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//
//        // 我
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "语音：25s");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_VOICE);
//        cv.put(ChatInfo.CHAT_SEND_STATE, ChatInfo.SEND_STATE_ARRIVED);
//        cv.put(ChatInfo.SEND_UID, GeePrefrence.getMyUid(this));
//        cv.put(ChatInfo.VOICE_PLAY_STATE, ChatInfo.VOICE_STATE_PLAYED);
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//
//        // 对方
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "语音：13s");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_VOICE);
//        cv.put(ChatInfo.VOICE_PLAY_STATE, ChatInfo.VOICE_STATE_NOT_PLAYED);
//        cv.put(ChatInfo.SEND_UID, friendUid);
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//        
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "语音：18s");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_VOICE);
//        cv.put(ChatInfo.VOICE_PLAY_STATE, ChatInfo.VOICE_STATE_PLAYING);
//        cv.put(ChatInfo.SEND_UID, friendUid);
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//        
//        // 我
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "地理消息");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_LOCATION);
//        cv.put(ChatInfo.CHAT_SEND_STATE, ChatInfo.SEND_STATE_FAIL);
//        cv.put(ChatInfo.SEND_UID, GeePrefrence.getMyUid(this));
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);
//        
//        // 对方
//        cv = new ContentValues();
//        cv.put(ChatInfo.CHAT_CONTENT, "地理消息");
//        cv.put(ChatInfo.SEND_DATE, new Date().getTime());
//        cv.put(ChatInfo.MSG_TYPE, ChatInfo.MSG_TYPE_LOCATION);
//        cv.put(ChatInfo.SEND_UID, friendUid);
//        cv.put(ChatInfo.FRIEND_UID, friendUid);
//        ChatInfo.saveChatInfo(getApplicationContext(), cv);

        Cursor chatInfoCursor = DataBaseHelper.getChatInfo(getApplicationContext(), friendUid);
        if(null != chatInfoCursor){
            startManagingCursor(chatInfoCursor);
        }else{
            LogUtil.e(TAG, "查询的cursor is null");
            finish();
            return;
        }
        
        mChatListView = (ListView) findViewById(R.id.chat_list_view);
        mChatListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        mChatListView.setDividerHeight(0);
        mChatAdapter = new ChatAdapter(this, R.layout.chat_list_item, chatInfoCursor, false);
        mChatListView.setAdapter(mChatAdapter);
        
    }
    
    private Cursor chatInfoCursor;
    private MediaPlayer mMediaPlayer;
    
    private void requery(){
        if(null != chatInfoCursor){
            chatInfoCursor.requery();
        }
    }
    
    private OnCompletionListener mOnCompletionListener = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            
        }
    };
    
    class PlayVoiceThread implements Runnable{

        private String voiceFilePath; 
        
        public PlayVoiceThread(String param){
            voiceFilePath = param;
        }
        
        @Override
        public void run() {
            if(null == mMediaPlayer){
                mMediaPlayer = new MediaPlayer();
            }
            mMediaPlayer.reset();
            mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mMediaPlayer.setDataSource(voiceFilePath);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            } catch (Exception e) {
                LogUtil.e(TAG, "播放语音有异常.", e);
            }
        }
    }

    private class ChatAdapter extends ResourceCursorAdapter {
        
        private SimpleDateFormat sdf;
        private ChatInfo chatInfo;

        public ChatAdapter(Context context, int layout, Cursor c, boolean autoRequery) {
            super(context, layout, c, autoRequery);
            this.sdf = new SimpleDateFormat("MM月dd日 HH:mm");
            this.chatInfo = new ChatInfo();
        }
        
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            
            chatInfo.setChatInfo(cursor);

            // 我的消息状态
            FrameLayout msgStateContainer = (FrameLayout) view.findViewById(R.id.msg_state_container);
            ProgressBar progressBar = (ProgressBar)msgStateContainer.findViewById(R.id.msg_state_sending);
            ImageView msgStateFail = (ImageView)msgStateContainer.findViewById(R.id.msg_state_fail);
            
            // 我的消息附件
            ImageView iv1 = (ImageView) view.findViewById(R.id.chat_item_image1);

            // 对方的消息附件
            ImageView iv2 = (ImageView) view.findViewById(R.id.chat_item_image2);

            ImageView friendAvatar = (ImageView) view.findViewById(R.id.friend_avatar);
            ImageView myAvatar = (ImageView) view.findViewById(R.id.my_avatar);

            TextView textMsgTextView = (TextView) view.findViewById(R.id.chat_msg_text_view);
            TextView msgDateTextView = (TextView) view.findViewById(R.id.chat_msg_date_text_view);

            LinearLayout innerContainer = (LinearLayout) view.findViewById(R.id.chat_item_inner_container);
            View textContainer = view.findViewById(R.id.chat_text_container);

            textMsgTextView.setText(chatInfo.chatContent);
            msgDateTextView.setText(sdf.format(new Date(chatInfo.sendDate)));
            
            textContainer.setOnClickListener(null);
            iv1.setOnClickListener(null);
            iv2.setOnClickListener(null);

            if (chatInfo.sendUid != GeePrefrence.getMyUid(ChatActivity.this)) { // 好友的消息

                myAvatar.setVisibility(View.GONE);
                friendAvatar.setVisibility(View.VISIBLE);

                msgStateContainer.setVisibility(View.GONE);
                iv1.setVisibility(View.GONE);

                innerContainer.setGravity(Gravity.LEFT);
                textContainer.setBackgroundResource(R.drawable.friend_text_container_bg);

                if (chatInfo.msgType==ChatInfo.MSG_TYPE_TEXT) {
                    iv2.setVisibility(View.GONE);
                } else if (chatInfo.msgType==ChatInfo.MSG_TYPE_VOICE) {
                    iv2.setVisibility(View.VISIBLE);
                    
                    //设置播放语音的监听
//                    textContainer.setOnClickListener(onVoiveClickListener);
//                    textContainer.setTag(chatInfo.voiceFileId);
//                    iv2.setOnClickListener(onVoiveClickListener);
//                    iv2.setTag(chatInfo.voiceFileId);
                    
                    if(chatInfo.voicePlayState==ChatInfo.VOICE_STATE_NOT_PLAYED){
                        iv2.setImageResource(R.drawable.voice_not_played);
                    }else if(chatInfo.voicePlayState==ChatInfo.VOICE_STATE_PLAYED){
                        iv2.setImageResource(R.drawable.friend_voice_icon);
                    }else if(chatInfo.voicePlayState==ChatInfo.VOICE_STATE_PLAYING){
                        iv2.setImageResource(R.anim.friend_play_voice_anim);
                        final AnimationDrawable ad = (AnimationDrawable)iv2.getDrawable();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                ad.start();
                            }
                        });
                    }
                } else if (chatInfo.msgType==ChatInfo.MSG_TYPE_LOCATION) {
                    iv2.setVisibility(View.VISIBLE);
                    iv2.setImageResource(R.drawable.chat_msg_location);
                }

            } else { // 自己的消息

                myAvatar.setVisibility(View.VISIBLE);
                friendAvatar.setVisibility(View.GONE);

                iv2.setVisibility(View.GONE);

                innerContainer.setGravity(Gravity.RIGHT);
                textContainer.setBackgroundResource(R.drawable.my_text_container_bg);

                if (chatInfo.sendState==ChatInfo.SEND_STATE_SENDING) {
                    msgStateContainer.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.VISIBLE);
                    msgStateFail.setVisibility(View.GONE);
                } else if (chatInfo.sendState==ChatInfo.SEND_STATE_FAIL) {
                    msgStateContainer.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                    msgStateFail.setVisibility(View.VISIBLE);
                } else if (chatInfo.sendState==ChatInfo.SEND_STATE_ARRIVED) {
                    msgStateContainer.setVisibility(View.GONE);
                }

                if (chatInfo.msgType==ChatInfo.MSG_TYPE_TEXT) {
                    iv1.setVisibility(View.GONE);
                } else if (chatInfo.msgType==ChatInfo.MSG_TYPE_VOICE) {
                    iv1.setVisibility(View.VISIBLE);
                    
                    //设置播放语音的监听
//                    textContainer.setOnClickListener(onVoiveClickListener);
//                    textContainer.setTag(chatInfo.voiceFileId);
//                    iv1.setOnClickListener(onVoiveClickListener);
//                    iv1.setTag(chatInfo.voiceFileId);
                    
                    if(chatInfo.voicePlayState==ChatInfo.VOICE_STATE_PLAYED){
                        iv1.setImageResource(R.drawable.my_voice_icon);
                    }else if(chatInfo.voicePlayState==ChatInfo.VOICE_STATE_PLAYING){
                        iv1.setImageResource(R.anim.my_play_voice_anim);
                        final AnimationDrawable ad = (AnimationDrawable)iv1.getDrawable();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                ad.start();
                            }
                        });
                    }
                } else if (chatInfo.msgType==ChatInfo.MSG_TYPE_LOCATION) {
                    iv1.setVisibility(View.VISIBLE);
                    iv1.setImageResource(R.drawable.chat_msg_location);
                }
            }
            
            
        } //bindView
        
    }

    private void toTextMode() {
        textViews.setVisibility(View.VISIBLE);

        if (null == leftAnimation) {
            leftAnimation = new Rotate3DAnimation(-90, 0, textViews.getWidth() / 2.0f, textViews.getHeight() / 2.0f);
            leftAnimation.setFillAfter(true);
            leftAnimation.setDuration(duration);
            leftAnimation.setInterpolator(new AccelerateInterpolator());
            leftAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    textViews.bringToFront();
                    voiceViews.setVisibility(View.GONE);
                }
            });
        }

        if (null == rightAnimation) {
            rightAnimation = new Rotate3DAnimation(0, 90, textViews.getWidth() / 2.0f, textViews.getHeight() / 2.0f);
            rightAnimation.setFillAfter(true);
            rightAnimation.setDuration(duration);
            rightAnimation.setInterpolator(new AccelerateInterpolator());
        }

        textViews.startAnimation(leftAnimation);
        voiceViews.startAnimation(rightAnimation);
    }

    private void toVoicetMode() {
        voiceViews.setVisibility(View.VISIBLE);

        if (null == leftAnimation2) {
            leftAnimation2 = new Rotate3DAnimation(0, -90, voiceViews.getWidth() / 2.0f, voiceViews.getHeight() / 2.0f);
            leftAnimation2.setFillAfter(true);
            leftAnimation2.setDuration(duration);
            leftAnimation2.setInterpolator(new AccelerateInterpolator());
            leftAnimation2.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    voiceViews.bringToFront();
                    textViews.setVisibility(View.GONE);
                }
            });
        }

        if (null == rightAnimation2) {
            rightAnimation2 = new Rotate3DAnimation(90, 0, voiceViews.getWidth() / 2.0f, voiceViews.getHeight() / 2.0f);
            rightAnimation2.setFillAfter(true);
            rightAnimation2.setDuration(duration);
            rightAnimation2.setInterpolator(new AccelerateInterpolator());
        }

        textViews.startAnimation(leftAnimation2);
        voiceViews.startAnimation(rightAnimation2);
    }

    @Override
    protected void onDestroy() {
        stopBindService();
        if (null != mMediaRecorder) {
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        super.onDestroy();
    }

}
